﻿using AutoMapper;
using System.Collections.Generic;

namespace Framework.Extensions
{
    /// <summary>
    /// AutoMapper即时注入并转换
    /// </summary>
    public static class AutoMapperExtensions
    {
        /// <summary>
        /// 即时注入对象并转换
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="maper"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static T2 IMap<T1, T2>(this IMapper maper, T1 source) where T1 : class where T2 : class
        {
            return source.IMap<T1, T2>();
        }
        /// <summary>
        /// 即时注入对象并转换
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="maper"></param>
        /// <param name="source"></param>
        /// <returns></returns>
        public static List<T2> IMap<T1, T2>(this IMapper maper, List<T1> source) where T1 : class where T2 : class
        {
            return source.IMap<T1, T2>();
        }

        /// <summary>
        /// 即时注入对象并转换
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static T2 IMap<T1, T2>(this T1 source) where T1 : class where T2 : class
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<T1, T2>();
            });

            var mapper = config.CreateMapper();
            return mapper.Map<T1, T2>(source);
        }

        /// <summary>
        /// 即时注入对象并转换
        /// </summary>
        /// <typeparam name="T1"></typeparam>
        /// <typeparam name="T2"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static List<T2> IMap<T1, T2>(this List<T1> source) where T1 : class where T2 : class
        {
            var config = new MapperConfiguration(cfg =>
            {
                cfg.CreateMap<T1, T2>();
            });

            var mapper = config.CreateMapper();

            return mapper.Map<List<T1>, List<T2>>(source);
        }
    }
}
